package com.lfs.dingtalk.robot.servcie;

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.aliyun.tea.*;

import static com.lfs.dingtalk.robot.constants.CommonConstant.APP_KEY;
import static com.lfs.dingtalk.robot.constants.CommonConstant.APP_SECRET;

@Service
@Slf4j
public class DingTalkService {


    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        return new com.aliyun.dingtalkoauth2_1_0.Client(new com.aliyun.teaopenapi.models.Config(){{
            protocol = "https";
            regionId = "central";
        }});
    }

    /**
     * 获取accessToken
     * @return
     */
    @SneakyThrows
    public static String getAccessToken() {
        com.aliyun.dingtalkoauth2_1_0.Client client = createClient();
        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                .setAppKey(APP_KEY)
                .setAppSecret(APP_SECRET);
        GetAccessTokenResponse response = new GetAccessTokenResponse();
        try {
            response = client.getAccessToken(getAccessTokenRequest);
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                log.error("获取token异常：{}", err.message);
                err.printStackTrace();
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                log.error("获取token异常：{}", err.message);
                err.printStackTrace();
            }

        }
        return response.getBody() != null ? response.getBody().getAccessToken() : null;
    }


}
